package com.android.jay.lib_audio.mediaplayer.core;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.util.Log;

import com.android.jay.lib_audio.app.AudioHelper;
import com.android.jay.lib_audio.mediaplayer.event.AudioCompletion;
import com.android.jay.lib_audio.mediaplayer.event.AudioErrorEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioPauseEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioProgressEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioReleaseEvent;
import com.android.jay.lib_audio.mediaplayer.event.AudioStartEvent;
import com.android.jay.lib_audio.mediaplayer.model.AudioBean;
import com.android.jay.lib_audio.mediaplayer.event.AudioLoadEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * Created by wzp on 2020/1/12 0012.
 * <p>
 * 描述  ：1.播放音频
 * 2.对外发送各种类型的事件
 */
public class AudioPlayer implements MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, AudioFocusManager.AudioFocusListener {


    private static final String TAG = "AudioPlayer";
    private static final int TIME_MSG = 0X01;
    private static final int TIME_INVAL = 100;

    //真正负责音频的播放
    private CustomMediaPlayer mMediaPlayer;
    //增加mediaplayer后台保活
    private WifiManager.WifiLock mWifiLock;
    //音频焦点监听器
    private AudioFocusManager audioFocusManager;
    private boolean isPauseByFocusLossTransient;  //该属性是判断是否是短暂失去焦点 导致暂停
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TIME_MSG:
                    //暂停也要更新进度，防止UI不同步，只不过进度一直一样
                    if (getStatus() == CustomMediaPlayer.Status.STARTED
                            || getStatus() == CustomMediaPlayer.Status.PAUSE) {
                        EventBus.getDefault().post(new AudioProgressEvent(getStatus(), getCurrentTime(), getTotalTime()));
                        mHandler.sendEmptyMessageDelayed(TIME_MSG, TIME_INVAL);
                    }
                    break;
            }
        }
    };

    public AudioPlayer() {
        init();
    }

    //初始化
    private void init() {
        mMediaPlayer = new CustomMediaPlayer();
        //电量微弱也保证 能够播放
        mMediaPlayer.setWakeMode(AudioHelper.getContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setCompleteListener(this);
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnBufferingUpdateListener(this);
        mMediaPlayer.setOnErrorListener(this);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //播放完毕发送的回调
                EventBus.getDefault().post(new AudioCompletion());

                Log.e("播放完毕","播放完毕！！！！！！！！！！！");
            }
        });
        //保活
        mWifiLock = ((WifiManager) AudioHelper
                .getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE))
                .createWifiLock(WifiManager.WIFI_MODE_FULL, TAG);
        //监听
        audioFocusManager = new AudioFocusManager(AudioHelper.getContext(), this);
    }

    //对外提供的音频加载方法
    public void load(AudioBean audioBean) {
        //资源错误的try catch
        try {
            // 清空数据
            mMediaPlayer.reset();
            //设置资源
            mMediaPlayer.setDataSource(audioBean.mUrl);
            //播放器异步准备 准备完毕会调用onPrepared
            mMediaPlayer.prepareAsync();
            //对外发送load 事件
            EventBus.getDefault().post(new AudioLoadEvent(audioBean));
        } catch (Exception e) {
            //对外发送error事件
            EventBus.getDefault().post(new AudioErrorEvent());
        }

    }

    //内部开始播放
    private void start() {
        if (!audioFocusManager.requestAudioFocus()) {
            Log.e(TAG, "获取音频焦点失败");
        }
        mMediaPlayer.start();
        mWifiLock.acquire();
        //更新进度
        mHandler.sendEmptyMessage(TIME_MSG);
        //对外发送start事件
        EventBus.getDefault().post(new AudioStartEvent());
    }

    //对外提供暂停
    public void pause() {
        if (getStatus() == CustomMediaPlayer.Status.STARTED) {
            mMediaPlayer.pause();
            //释放wifilock
            if (mWifiLock.isHeld()) {
                mWifiLock.release();
            }
            //将focus也释放掉 让其他应用使用
            if (audioFocusManager != null) {
                audioFocusManager.abandonAudioFocus();
            }
            // 对外发送暂停事件
            EventBus.getDefault().post(new AudioPauseEvent());
        }
    }

    //对外提供恢复
    public void resume() {
        if (getStatus() == CustomMediaPlayer.Status.PAUSE) {
            //直接复用start
            start();
        }
    }

    /**
     * 清空播放器资源
     **/
    public void release() {
        if (mMediaPlayer == null) {
            return;
        }
        mMediaPlayer.release();
        mMediaPlayer = null;

        if (mWifiLock.isHeld()) {
            mWifiLock.release();
        }
        if (audioFocusManager != null) {
            audioFocusManager.abandonAudioFocus();
        }
        mWifiLock = null;
        audioFocusManager = null;
        //发送release销毁事件
        EventBus.getDefault().post(new AudioReleaseEvent());
    }

    /**
     * 获取播放器状态
     **/
    public CustomMediaPlayer.Status getStatus() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.getState();
        }
        return CustomMediaPlayer.Status.STOPPTED;
    }

    /**
     * @param leftv  左声道
     * @param rightv 右声道
     **/
    private void setVolumn(float leftv, float rightv) {
        if (mMediaPlayer != null) {
            mMediaPlayer.setVolume(leftv, rightv);
        }
    }


    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        //缓存进度回调

    }

    @Override
    public void onCompletion(MediaPlayer mp) {

        //播放完毕发送的回调
        EventBus.getDefault().post(new AudioCompletion());

        Log.e("播放完毕","播放完毕！！！！！！！！！！！");


    }

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        //播放出错回调
        EventBus.getDefault().post(new AudioErrorEvent());
        //返回为true 一旦error事件发生就不在回调oncompletion方法
        return true;
    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        //准备完毕 自动进入播放状态
        start();
    }


    @Override
    public void audioFocusGrant() {
        //再次获得音频焦点
        setVolumn(1.0f, 1.0f);
        if (isPauseByFocusLossTransient) {
            resume();
        }
        isPauseByFocusLossTransient = false;
    }


    @Override
    public void audioFocusLoss() {
        //永久失去焦点
        pause();
    }

    @Override
    public void audioFocusLossTransient() {
        //短暂性失去焦点
        pause();
        isPauseByFocusLossTransient = true;
    }

    @Override
    public void audioFocusLossDuck() {
        // 瞬间失去焦点
        setVolumn(0.5f, 0.5f);
    }


    /**
     * 获取音频时间 用来更新UI
     **/
    private int getTotalTime() {
        if (getStatus() == CustomMediaPlayer.Status.STARTED
                || getStatus() == CustomMediaPlayer.Status.PAUSE) {
            return mMediaPlayer.getDuration();
        }
        return 0;
    }

    private int getCurrentTime() {
        if (getStatus() == CustomMediaPlayer.Status.STARTED
                || getStatus() == CustomMediaPlayer.Status.PAUSE) {
            return mMediaPlayer.getCurrentPosition();
        }
        return 0;
    }

    /**对外设置进度**/
    public void setMusicCurrentTime(int time){
        mMediaPlayer.seekTo(time);
    }


}
